package cn.iocoder.yudao.module.system.controller.admin.wishlist;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.wishlist.vo.*;
import cn.iocoder.yudao.module.system.convert.wishlist.UserWishListConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.wishlist.UserWishListDO;
import cn.iocoder.yudao.module.system.service.wishlist.UserWishListService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 用户志愿表公开 Controller（无需权限验证）
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 用户志愿表（公开接口）")
@RestController
@RequestMapping("/system/user-wish-list/public")
@Validated
@Slf4j
public class UserWishListPublicController {

    @Resource
    private UserWishListService userWishListService;

    @PostMapping("/create")
    @Operation(summary = "添加专业到志愿表",
            description = "用户可以将从专业推荐接口获取的专业信息添加到个人志愿表中")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:create') or permitAll()")
    public CommonResult<Long> createUserWishList(@Valid @RequestBody UserWishListCreateReqVO createReqVO,
                                                  @RequestParam("userId") Long userId) {
        return success(userWishListService.createUserWishList(createReqVO, userId));
    }

    @PostMapping("/create-from-major")
    @Operation(summary = "从专业信息直接添加到志愿表",
            description = "便捷方法：直接从getAllSuitableMajorsByParams接口返回的专业信息创建志愿")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:create') or permitAll()")
    public CommonResult<Long> createUserWishListFromMajor(@Valid @RequestBody UserWishListFromMajorReqVO fromMajorReqVO) {
        // 转换为标准的创建请求
        UserWishListCreateReqVO createReqVO = UserWishListConvert.INSTANCE.convertFromMajor(fromMajorReqVO);
        return success(userWishListService.createUserWishList(createReqVO, fromMajorReqVO.getUserId()));
    }

    @PutMapping("/update")
    @Operation(summary = "更新志愿信息")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:update') or permitAll()")
    public CommonResult<Boolean> updateUserWishList(@Valid @RequestBody UserWishListUpdateReqVO updateReqVO,
                                                     @RequestParam("userId") Long userId) {
        userWishListService.updateUserWishList(updateReqVO, userId);
        return success(true);
    }

    @GetMapping("/delete")
    @Operation(summary = "从志愿表中删除专业")
    @Parameter(name = "id", description = "志愿ID", required = true)
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:delete') or permitAll()")
    public CommonResult<Boolean> deleteUserWishList(@RequestParam("id") Long id,
                                                     @RequestParam("userId") Long userId) {
        userWishListService.deleteUserWishList(id, userId);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "查看我的志愿表", 
            description = "获取用户的完整志愿表，按志愿类型和顺序排列")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<List<UserWishListRespVO>> getUserWishListByUserId(@RequestParam("userId") Long userId) {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserId(userId);
        return success(UserWishListConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-by-type")
    @Operation(summary = "按类型查看志愿表")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @Parameter(name = "wishType", description = "志愿类型：rush-冲刺，stable-稳妥，safe-保底", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<List<UserWishListRespVO>> getUserWishListByUserIdAndWishType(@RequestParam("userId") Long userId,
                                                                                      @RequestParam("wishType") String wishType) {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserIdAndWishType(userId, wishType);
        return success(UserWishListConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/grouped")
    @Operation(summary = "查看志愿表（按类型分组）", 
            description = "返回按冲刺、稳妥、保底三个类型分组的志愿表数据")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<Map<String, List<UserWishListRespVO>>> getUserWishListGrouped(@RequestParam("userId") Long userId) {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserId(userId);
        Map<String, List<UserWishListRespVO>> grouped = UserWishListConvert.INSTANCE.convertList(list)
                .stream()
                .collect(Collectors.groupingBy(UserWishListRespVO::getWishType));
        return success(grouped);
    }

    @PostMapping("/update-order")
    @Operation(summary = "调整志愿顺序", 
            description = "用户可以调整同一类型志愿的排列顺序")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @Parameter(name = "wishType", description = "志愿类型", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:update') or permitAll()")
    public CommonResult<Boolean> updateWishOrder(@RequestParam("userId") Long userId,
                                                  @RequestParam("wishType") String wishType,
                                                  @RequestBody List<Long> wishListIds) {
        userWishListService.updateWishOrder(userId, wishType, wishListIds);
        return success(true);
    }

    @GetMapping("/check-exists")
    @Operation(summary = "检查专业是否已在志愿表中", 
            description = "在添加专业前检查是否已经存在，避免重复添加")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @Parameter(name = "schoolUuid", description = "学校UUID", required = true)
    @Parameter(name = "majorName", description = "专业名称", required = true)
    @Parameter(name = "year", description = "年份", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<Boolean> checkWishListExists(@RequestParam("userId") Long userId,
                                                      @RequestParam("schoolUuid") String schoolUuid,
                                                      @RequestParam("majorName") String majorName,
                                                      @RequestParam("year") Integer year) {
        boolean exists = userWishListService.isWishListExists(userId, schoolUuid, majorName, year);
        return success(exists);
    }

    @GetMapping("/count-by-type")
    @Operation(summary = "获取指定类型志愿数量")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @Parameter(name = "wishType", description = "志愿类型", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<Long> getWishListCountByUserIdAndWishType(@RequestParam("userId") Long userId,
                                                                   @RequestParam("wishType") String wishType) {
        Long count = userWishListService.getWishListCountByUserIdAndWishType(userId, wishType);
        return success(count);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查看志愿表")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query') or permitAll()")
    public CommonResult<PageResult<UserWishListRespVO>> getUserWishListPage(@RequestParam("userId") Long userId,
                                                                             @Valid UserWishListPageReqVO pageReqVO) {
        // 设置用户ID，确保只能查看指定用户的志愿
        pageReqVO.setUserId(userId);
        PageResult<UserWishListDO> pageResult = userWishListService.getUserWishListPage(pageReqVO);
        return success(UserWishListConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-file")
    @Operation(summary = "导出用户志愿表并返回下载链接",
            description = "导出指定用户的志愿表为Excel文件，返回文件下载链接")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:export') or permitAll()")
    public CommonResult<String> exportUserWishListFile(@RequestParam("userId") Long userId,
                                                        @Valid UserWishListPageReqVO pageReqVO) {
        String fileUrl = userWishListService.exportUserWishListToFile(pageReqVO, userId);
        return success(fileUrl);
    }

}
